<template>
  <el-card style="width: 1000PX;height: 1000px;">
    <!-- 第一个对话框 -->
    <el-dialog v-model="Slaughtslog1" title="Tips" style="height: auto;width: 500px;">
      <el-form :model="ftableData" label-width="auto" style="max-width: 600px">
        <el-form-item label="批次">
          <el-input v-model="ftableData.slaught_Batch" maxlength="30" />
        </el-form-item>
        <el-form-item label="到厂均重(公斤)">
          <el-input v-model="ftableData.slaught_Heaving" maxlength="5" />
        </el-form-item>
        <el-form-item label="到厂时间">
          <el-date-picker v-model="ftableData.slaught_ActionTime" type="date" placeholder="请输入日期" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="屠宰时间">
          <el-date-picker v-model="ftableData.slaught_Time" type="date" placeholder="请输入日期" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="SlaughtsEdit1()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <span
      style="font-size: 24px;color:dodgerblue;">屠宰信息&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <el-button plain @click="Sublog1()" style="background: #f1f2f7;color:black;border:none;margin-left: 10px;">
      设置
    </el-button>
    <br />
    <!-- 六条信息显示 -->
    <span style="font-size: 16px;color: black;">
      批次:
      {{ tableData.slaught_Batch
      }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      到厂均重:
      {{ tableData.slaught_Heaving }}公斤
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      到厂时间:
      {{ tableData.slaught_ActionTime.toString().replace("T", " ").substring(0, 10)
      }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      屠宰时间:
      {{ tableData.slaught_Time.toString().replace("T", " ").substring(0, 10) }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      <!-- 图片预览地址 -->
      <el-dialog v-model="dialogVisible1">
        <img w-full :src="dialogImageUrl1" />
      </el-dialog>
      <!-- 上传图片以','分开存储字符串 -->
      <el-upload class="avatar-uploader" v-model:file-list="fileList1" action="http://localhost:5094/api/Fileall/Fileup"
        :on-success="handleAvatarSuccess1" list-type="picture-card" :before-upload="beforeAvatarUpload1"
        :on-remove="handleRemove1" :on-preview="handlePictureCardPreview1" :limit="9">

        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

    </span>
    <br />
    <el-dialog v-model="Slaughtslog2" title="Tips" style="height: auto;width: 500px;">
      <el-form :model="FnextWortk" label-width="auto" style="max-width: 600px">
        <el-form-item label="公司名称">
          <el-input v-model="FnextWortk.company" maxlength="30"/>
        </el-form-item>
        <el-form-item label="成立时间">
          <el-date-picker v-model="FnextWortk.company_Time" type="date" placeholder="请输入日期" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="公司地址">
               <el-select v-model="ruleForm.addressId" placeholder="请选择省份" style="width: 33%;">
          <el-option v-for="itme in sadr1" :value="itme.sheng_Id" :label="itme.sheng_Name"
            @click="SPlease2(itme.sheng_Id)" />
        </el-select>
        <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width: 33%;">
          <el-option v-for="itme in sadr2" :value="itme.city_Id" :label="itme.city_Name" @click="SPlease3(itme.city_Id)" />
        </el-select>
        <el-select v-model="ruleForm.xianId" placeholder="请选择县" style="width: 33%;">
          <el-option v-for="itme in sadr3" :value="itme.xian_Id" :label="itme.xian_Name" />
        </el-select>
        </el-form-item>
        <el-form-item label="公司简介">
          <el-input v-model="FnextWortk.company_Content"  type="textarea" maxlength="500"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="SlaughtsEdit2()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <span style="font-size: 24px;color:dodgerblue;">企业信息&nbsp;&nbsp;</span>
    <button style="background: #f1f2f7;color:black;border:none;margin-left: 10px;" @click="Sublog2()">设置</button>
    <br />
    <!-- 三条信息显示 -->
    <span style="font-size: 16px;color: black;">
      公司名称:
      {{ NextWortk.company
      }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      成立时间:
      {{ NextWortk.company_Time.toString().replace("T", " ").substring(0, 10) }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      公司地址:
      {{ NextWortk.company_Path }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      公司简介:
      {{ NextWortk.company_Content }}
    </span>
    <br />
    <!-- 利用数组的上传 -->
    <span style="font-size: 16px;color: black;">
      <!-- 图片预览地址 -->
      <el-dialog v-model="dialogVisible2">
        <img w-full :src="dialogImageUrl2" />
      </el-dialog>
      <!-- 上传图片以','分开存储字符串 -->
      <el-upload class="avatar-uploader" v-model:file-list="fileList2" action="http://localhost:5094/api/Fileall/Fileup"
        :on-success="handleAvatarSuccess2" list-type="picture-card" :before-upload="beforeAvatarUpload2"
        :on-remove="handleRemove2" :on-preview="handlePictureCardPreview2" :limit="9">

        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

    </span>
  </el-card>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
const Slaughtslog1 = ref(false)
const Slaughtslog2 = ref(false)

const tableData = reactive({
  slaught_Id: 0,
  rabit_Batch: location.search.split("=")[1],
  slaught_Batch: "",
  slaught_Heaving: "",
  slaught_ActionTime: "",
  slaught_Time: "",
  slaught_Img: "",
  companyimg: "",
  company_IsDel: false
})
const ftableData = reactive({
  slaught_Id: 0,
  rabit_Batch: location.search.split("=")[1],
  slaught_Batch: "",
  slaught_Heaving: "",
  slaught_ActionTime: "",
  slaught_Time: "",
  slaught_Img: "",
  companyimg: "",
  company_IsDel: false
})

const NextWortk = reactive({
  slaughts_NextId: 0,
  rabit_Batch: location.search.split("=")[1],
  company: "",
  company_Time: "",
  company_Path: "",
  company_Content: ""
})
const FnextWortk = reactive({
  slaughts_NextId: 0,
  rabit_Batch: location.search.split("=")[1],
  company: "",
  company_Time: "",
  company_Path: "",
  company_Content: ""
})
const ruleForm = reactive({
  addressId: "",
  cityId: "",
  xianId: "",
})
onMounted(() => {
  FirstShow1()
  FirstShow2()
  SPlease1()
})
//填充数据1
const FirstShow1 = () => {
  axios.get("http://localhost:5094/api/SlaughtsAll/FistSlaughts", {
    params: {
      Batch: tableData.rabit_Batch
    }
  })
    .then(res => {
      ElMessage.success(res.data.message)
      tableData.slaught_Id = res.data.data.slaught_Id
      tableData.slaught_Batch = res.data.data.slaught_Batch
      tableData.slaught_Heaving = res.data.data.slaught_Heaving
      tableData.slaught_ActionTime = res.data.data.slaught_ActionTime
      tableData.slaught_Time = res.data.data.slaught_Time
      ftableData.slaught_Img = res.data.data.slaught_Img
      ftableData.companyimg = res.data.data.companyimg
      initImageList1()
      initImageList2()
    })
}//填充数据2
const FirstShow2 = () => {
  axios.get("http://localhost:5094/api/Slaughts_NextAll/FirstNextSlaughts", {
    params: {
      Batch: NextWortk.rabit_Batch
    }
  })
    .then(res => {
      ElMessage.success(res.data.message)
      NextWortk.slaughts_NextId = res.data.data.slaught_NextId
      NextWortk.company = res.data.data.company
      NextWortk.company_Time = res.data.data.company_Time
      NextWortk.company_Path = res.data.data.company_Path
      NextWortk.company_Content = res.data.data.company_Content
    })
}

//打开第一个屠宰信息弹窗
const Sublog1 = () => {
  Slaughtslog1.value = true
}//打开第二个屠宰信息弹窗
const Sublog2 = () => {
  Slaughtslog2.value = true
}
//保存屠宰信息
const SlaughtsEdit1 = () => {
      if (isNaN(Number(ftableData.slaught_Heaving))||ftableData.slaught_Heaving == "" || ftableData.slaught_ActionTime == "" || ftableData.slaught_Time == "") {
      ElMessage.error("信息不能为空,均重为数字")
      return
    }
  if (tableData.slaught_Id == 0) {//添加养殖表数据
    axios.post("http://localhost:5094/api/SlaughtsAll/AddSlaughts", ftableData)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow1()
        ftableData.slaught_Batch = ""
        ftableData.slaught_Heaving = ""
        ftableData.slaught_ActionTime = ""
        ftableData.slaught_Time = ""
        Slaughtslog1.value = false
      })
  }
  else {//修改养殖表数据
    ftableData.slaught_Id = tableData.slaught_Id
    axios.post("http://localhost:5094/api/SlaughtsAll/UpdateSlaughts", ftableData)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow1()
          ftableData.slaught_Batch = ""
        ftableData.slaught_Heaving = ""
        ftableData.slaught_ActionTime = ""
        ftableData.slaught_Time = ""
        Slaughtslog1.value = false
      })
  }
}
const SlaughtsEdit2 = () => {
    FnextWortk.company_Path=ruleForm.addressId.toString()+","+ruleForm.cityId.toString()+","+ruleForm.xianId.toString()
    if (ruleForm.xianId == ""||ruleForm.addressId == "" ||ruleForm.cityId ==""  ||FnextWortk.company == "" || FnextWortk.company_Time == ""  || FnextWortk.company_Content == "") {
      ElMessage.error("信息不能为空")
      return
    }
  if (NextWortk.slaughts_NextId == 0) {//公司表数据
      
    axios.post("http://localhost:5094/api/Slaughts_NextAll/AddNextSlaughts", FnextWortk)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow2()
        FnextWortk.company = ""
        FnextWortk.company_Time = ""
        FnextWortk.company_Path = ""
        FnextWortk.company_Content = ""
        Slaughtslog2.value = false
      })
  }
  else {//修改公司表数据
    
    FnextWortk.slaughts_NextId = NextWortk.slaughts_NextId
    axios.post("http://localhost:5094/api/Slaughts_NextAll/UpdateNextSlaughts", FnextWortk)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow2()
        FnextWortk.company = ""
        FnextWortk.company_Time = ""
        FnextWortk.company_Path = ""
        FnextWortk.company_Content = ""
        Slaughtslog2.value = false
      })
  }
}

//限制动检证的图片
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}//限制企业照片的图片
const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}
const fileList1 = ref<UploadUserFile[]>([])
const fileList2 = ref<UploadUserFile[]>([])
// 初始化图片列表
const initImageList1 = () => {
  if (ftableData.slaught_Img && ftableData.slaught_Img !== '') {
    const imageUrls = ftableData.slaught_Img.split(',').filter(url => url.trim() !== '')
    fileList1.value = imageUrls.map((url, index) => ({
      name: `image_${index + 1}.jpg`,
      url: url.trim()
    }))
  } else {
    fileList1.value = []
  }
}
// 初始化图片列表
const initImageList2 = () => {
  if (ftableData.companyimg && ftableData.companyimg !== '') {
    const imageUrls = ftableData.companyimg.split(',').filter(url => url.trim() !== '')
    fileList2.value = imageUrls.map((url, index) => ({
      name: `image_${index + 1}.jpg`,
      url: url.trim()
    }))
  } else {
    fileList2.value = []
  }
}
// 添加新上传的图片到数组，并更新到数据库中
const handleAvatarSuccess1: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  const newImageUrl = response.data
  if (ftableData.slaught_Img && ftableData.slaught_Img !== '') {
    ftableData.slaught_Img += ',' + newImageUrl
  } else {
    ftableData.slaught_Img = newImageUrl
  }

  // 保存到数据库
  saveImagesToDatabase1()

  ElMessage.success('图片上传成功')
}
const handleAvatarSuccess2: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // 再次检查图片数量限制（双重保险）
  const currentImageCount = ftableData.companyimg ?
    ftableData.companyimg.split(',').filter(url => url.trim() !== '').length : 0
  if (currentImageCount >= 9) {
    ElMessage.error('最多只能上传9张图片')
    return
  }
  const newImageUrl = response.data
  if (ftableData.companyimg && ftableData.companyimg !== '') {
    ftableData.companyimg += ',' + newImageUrl
  } else {
    ftableData.companyimg = newImageUrl
  }

  // 保存到数据库
  saveImagesToDatabase2()

  ElMessage.success('图片上传成功')
}

const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 从数组中移除对应的图片URL
  const imageUrls = ftableData.slaught_Img.split(',').filter(url => url.trim() !== '')
  const index = imageUrls.findIndex(url => url === uploadFile.url)

  if (index > -1) {
    imageUrls.splice(index, 1)
    ftableData.slaught_Img = imageUrls.join(',')
    // 更新数据库
    saveImagesToDatabase1()
    ElMessage.success('图片删除成功')
  }
}
const handleRemove2: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 从数组中移除对应的图片URL
  const imageUrls = ftableData.companyimg.split(',').filter(url => url.trim() !== '')
  const index = imageUrls.findIndex(url => url === uploadFile.url)

  if (index > -1) {
    imageUrls.splice(index, 1)
    ftableData.companyimg = imageUrls.join(',')
    // 更新数据库
    saveImagesToDatabase2()
    ElMessage.success('图片删除成功')
  }
}
// 保存图片数组到数据库1
const saveImagesToDatabase1 = () => {
  axios.get('http://localhost:5094/api/SlaughtsAll/CheckSlaughtsImages', {
    params: {
      Batch: ftableData.rabit_Batch,
      CheckImages: ftableData.slaught_Img
    }
  }).then(res => {
    ElMessage.success('图片保存成功')
  }).catch(err => {
    ElMessage.error('图片保存失败: ' + err.message)
  })
}// 保存图片数组到数据库2
const saveImagesToDatabase2 = () => {
  axios.get('http://localhost:5094/api/SlaughtsAll/CheckSlauCompanyImages', {
    params: {
      Batch: ftableData.rabit_Batch,
      CheckImages: ftableData.companyimg
    }
  }).then(res => {
    ElMessage.success('图片保存成功')
  }).catch(err => {
    ElMessage.error('图片保存失败: ' + err.message)
  })
}
//图片地址
const dialogImageUrl1 = ref('')
//图片弹窗
const dialogVisible1 = ref(false)
//图片地址
const dialogImageUrl2 = ref('')
//图片弹窗
const dialogVisible2 = ref(false)
//图片预览1
const handlePictureCardPreview1: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!
  dialogVisible1.value = true
}
//图片预览2
const handlePictureCardPreview2: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl2.value = uploadFile.url!
  dialogVisible2.value = true
}
const sadr1 = ref([{
    sheng_Id: 0,
      sheng_Name: ""
}])
const sadr2 = ref([{
  city_Id: 0,
      sheng_Id: 0,
      city_Name: ""
}])
const sadr3 = ref([{
  xian_Id: 0,
      city_Id: 0,
      xian_Name: ""
}])
//第一级联动
const SPlease1 = () => {
  axios.get("http://localhost:5094/api/ThreeSelectAll/TreeSheng/TreeSheng").then(res => {
    sadr1.value = res.data.data
  })
}
//第二级联动
const SPlease2 = (id: number) => {
  ruleForm.cityId = ""
  ruleForm.xianId = ""
  axios.get("http://localhost:5094/api/ThreeSelectAll/TreeCity/TreeCity", {
    params: {
      ShengId: id
    }
  }).then(res => {
    sadr2.value = res.data.data
  })
}
//第三级联动
const SPlease3 = (id: number) => {
  ruleForm.xianId = ""
  axios.get("http://localhost:5094/api/ThreeSelectAll/TreeXian/TreeXian", {
    params: {
      CityId: id
    }
  }).then(res => {
    sadr3.value = res.data.data
  })
}
</script>

<!-- 使用黑色实线边框,加号，边框 -->
<style>
.avatar-uploader .el-upload {
  border: 1px solid var(--el-border-color);
  border-color: black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 17px;
  color: black;
  width: 17px;
  height: 17px;
  text-align: center;
}
</style>